import time

import requests

import requests

def get_turnover():
    url = "https://dq.10jqka.com.cn/fuyao/market_analysis_api/chart/v1/get_chart_data"
    params = {
        "chart_key": "turnover_minute"
    }

    headers = {
        "Host": "dq.10jqka.com.cn",
        "Connection": "keep-alive",
        "sec-ch-ua-platform": "Android",
        "User-Agent": "Mozilla/5.0 (Linux; Android 15; 2410DPN6CC Build/AQ3A.240812.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/134.0.6998.135 Mobile Safari/537.36 Hexin_Gphone/11.26.02 (Royal Flush)",
        "Accept": "application/json, text/plain, */*",
        "sec-ch-ua": '"Chromium";v="134", "Not:A-Brand";v="24", "Android WebView";v="134"',
        "sec-ch-ua-mobile": "?1",
        "Origin": "https://eq.10jqka.com.cn",
        "X-Requested-With": "com.hexin.plat.android",
        "Sec-Fetch-Site": "same-site",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": "https://eq.10jqka.com.cn/",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
        "Cookie": "user=MDptb180Nzc0MjQzMzc6Ok5vbmU6NTAwOjQ4NzQyNDMzNzo1LDEsNDA7NiwxLDQwOzcsMTExMTExMTExMTEwLDQwOzgsMTExMTAxMTEwMDAwMTExMTEwMDEwMDEwMDEwMDAwMDAsNDA7MzMsMDAwMTAwMDAwMDAwLDIzNjszNiwxMDAxMTExMTAwMDAxMTAwMTAxMTExMTEsMjM2OzQ2LDAwMDAxMTExMTAwMDAwMTExMTExMTExMSwyMzY7NTEsMTEwMDAwMDAwMDAwMDAwMCwyMzY7NTgsMDAwMDAwMDAwMDAwMDAwMDEsMjM2Ozc4LDEsMjM2Ozg3LDAwMDAwMDAwMDAwMDAwMDAwMDAxMDAwMCwyMzY7MTE5LDAwMDAwMDAwMDAwMDAwMDAwMDEwMTAwMDAwMDAwMCwyMzY7MTI1LDExLDIzNjs0NCwxMSw0MDsxLDEwMSw0MDsyLDEsNDA7MywxLDQwOzEwMiwxLDQwOjI0Ojo6NDc3NDI0MzM3OjE3NDM2NDk1MDE6OjoxNTUxNDA3MDQwOjQ4OTI5OTowOjExMDA5YjUxOTViMzEyN2U3ZmJlOTE3MDgzM2ExNDg5MDo6MQ%3D%3D; userid=477424337; u_name=mo_477424337; escapename=mo_477424337; ticket=0b931e603ea0d3f4b6023f224bb4e79b; user_status=0; hxmPid=hqMarketPkgVersionControl; v=A7uJmuXpWDa08WSCjdpz8L6MS5QlEM8SySSTxq14l7rRDNRONeBfYtn0IxG-"
    }

    response = requests.get(
        url,
        params=params,
        headers=headers,
        verify=True  # 如需忽略SSL验证可改为False
    )
    # 从响应数据中提取关键指标
    response_data = response.json()
    # 从响应数据中提取关键指标
    # 假设 header_data 是从 response_data['data']['charts']['header'] 提取的
    header_data = response_data['data']['charts']['header']

    result = {
        '当日成交额': next((item['val'] for item in header_data if item['key'] == 'turnover'), None),
        '昨日成交额': next((item['val'] for item in header_data if item['key'] == 'turnover_pre'), None),
        '较昨日变动': next((item['val'] for item in header_data if item['key'] == 'turnover_change'), None),
        '预测全天成交额': next((item['val'] for item in header_data if item['key'] == 'predict_turnover'), None)
    }
    # 转换单位到亿元（假设原始数据单位是分/元）
    result = {k: round(v / 1e8, 2) for k, v in result.items()}  # 除以1e8将分转亿元（1亿元=1e8分）

    for k, v in result.items():
        print(f"{k}: {v:,.2f} 亿")  # 打印结果以便调试

# print(response.status_code)
# print(response.json())  # 如果返回JSON数据


def get_market_score():

    url = "https://dq.10jqka.com.cn/fuyao/market_analysis_api/score/v1/get_market_score"

    headers = {
        "Host": "dq.10jqka.com.cn",
        "Connection": "keep-alive",
        "sec-ch-ua-platform": "Android",
        "User-Agent": "Mozilla/5.0 (Linux; Android 15; 2410DPN6CC Build/AQ3A.240812.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/134.0.6998.135 Mobile Safari/537.36 Hexin_Gphone/11.26.02 (Royal Flush)",
        "Accept": "application/json, text/plain, */*",
        "sec-ch-ua": '"Chromium";v="134", "Not:A-Brand";v="24", "Android WebView";v="134"',
        "sec-ch-ua-mobile": "?1",
        "Origin": "https://eq.10jqka.com.cn",
        "X-Requested-With": "com.hexin.plat.android",
        "Sec-Fetch-Site": "same-site",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": "https://eq.10jqka.com.cn/",
        "Accept-Encoding": "gzip, deflate, br, zstd",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
        "Cookie": "user=MDptb180NzOiQ2Mzc60k5vbmU6NTAwOjQ4NzQyNDMzNzo1LDESNDATNiwxLDQwOzcSMTExMTExMTExMTEwLDQwOzgsMTExMTAxMTEwMDAwMTExMTEwMDEwMDEwMDAwMDAsNDATMzMsMDAwMTAwMDAwMDAwLDizNjszNiwxMDAMTExMTAwMDAwMTAwMTAxMTExMTEsMjM2OzQ6LDAwMDAxMTExMTAwMDAwMTExMTExMTExMSwyMzY7NTEsMTEwMDAwMDAwMDAwMDAwMCwyMzY7NTgsMDAwMDAwMDAwMDAwMDEsMjM2OzC4LDEsMjM2Ozg3LDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMCwyMzY7MTE5LDAwMDAwMDAwMDAwMDAwMDAwMDEwMTAwMDAwMDAwMCwyMzY7MTILDExLDizNjsONCwxMSwOMDSxLDEWMSwOMDsyLDESNDATMywxLDQwOzEwMiwxLDQwOjIOojOsDc3NDIOMzM3OjE3NDM2NDkIMDE6OjoXNTUXNDA3MDQwOjQ4OTI5OTowOjExMDA5YjUxOTViMzEyNJZmJIOTE3MDgzM2EXNDg5MDo6MQ%3D%3D; userid=477424337; u_name=mo_477424337; escapename=mo_477424337; ticket=0b931e603ea0d3f4b6023f224bb4e79b; user_status=0; hxmPid=haMarketPkgVersionControl; v=A9vpOsVOJDXTOTipy97KJ5sazRFsO-y6cSzzsOYtlrxrPQuVYB_AvmUQ7He"
    }

    response = requests.get(
        url,
        headers=headers,
        verify=True  # 如需忽略SSL验证可改为False
    )

    print(response.status_code)
    if response.status_code == 200:
        print(response.json())  # 如果返回JSON数据
    else:
        print("请求失败:", response.text)

def fetch_data(code):
    # 补全 URL（原始链接被截断，推测完整路径）
    url = "https://dataq.10jqka.com.cn/fetch-data-server/fetch/v1/specific_data"

    # 修正后的请求头（过滤冗余字段）
    headers = {
        "Platform": "mobileweb",
        "Source-id": "constituent-stock",
        "Content-Length": "691",
        "Host": "dataq.10jqka.com.cn",
        "Connection": "Keep-Alive",
        "Accept-Encoding": "gzip",
        "User-Agent": "Mozilla/5.0 (Linux; Android 15; 2410DPN6CC Build/AQ3A.240812.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/134.0.6998.135 Mobile Safari/537.36 Hexin_Gphone/11.26.02 (Royal Flush)",
        "Content-Type": "application/json"  # 按实际类型调整
        # "Cookie": "user=H0p16R0NzOtMQ2Mzc0J6vbmU8NTAwQQAiXaQ; yNDMzNzuLDEsMDATNiKuADQwDZxFMTEeMTEeMTEeMTEeMLQQ; wQgapHTEeMTAoHTEeWbDAwMDDeMTEeMTEeWbDawMDDeWMDDeWMDAA",
        # 拼接多行 Cookie
    }

    # 若需要请求体（根据接口文档补充）
    payload = {
        "code_selectors": {
            "intersection": [
                {
                    "type": "hq_block_code",
                    "values": [
                        f"48:{code}"
                    ]
                }
            ]
        },
        "indexes": [
            {"index_id": "security_name"},
            {"index_id": "last_price"},
            {"index_id": "hq-fncdict-199112"},
            {"index_id": "hq-fncdict-3250"},
            {"index_id": "hq-fncdict-3475914"},
            {"index_id": "hq-fncdict-3541450"},
            {"index_id": "hq-fncdict-133957"},
            {"index_id": "hq-fncdict-527526"},
            {"index_id": "hq-fncdict-1968584"},
            {"index_id": "turnover"},
            {"index_id": "total_share_cnt", "time_type": "DAY_1", "timestamp": 0},
            {"index_id": "hq-fncdict-1771976"},
            {"index_id": "hq-fncdict-199189"},
            {"index_id": "F10-pb_mrq"},
            {"index_id": "hq-fncdict-526792"}
        ],
        "page_info": {
            "page_begin": 0,
            "page_size": 15,
            "code_begin": 0
        },
        "sort": [
            {"idx": 2, "type": "DESC"}
        ]
    }
    all_results = []
    page_begin = 0
    page_size = 15
    while True:
        payload["page_info"]["page_begin"] = page_begin
        payload["page_info"]["page_size"] = page_size
        try:
            response = requests.post(
                url,
                headers=headers,
                json=payload,  # 或 data=payload（表单格式）
                verify=True,  # SSL 验证
                timeout=30  # 增加超时时间
            )
            response.raise_for_status()  # 自动检查 HTTP 错误
            print(f"状态码: {response.status_code}")
            data = response.json()['data']
            if "data" in data :
                items = data["data"]
















                if not items:
                    break
                all_results.extend(items)
                page_begin += len(items)
                print(f"已获取 {len(items)} 条数据")
            else:
                print("未找到 'data' 字段")
                break

        except requests.exceptions.SSLError:
            print("SSL 证书验证失败，可临时设置 verify=False（不推荐）")
            break
        except requests.exceptions.RequestException as e:
            print(f"请求异常: {e}")
            time.sleep(5)  # 等待一段时间后重试
            continue
    print(f"总共获取 {len(all_results)} 条记录")
    return all_results

if __name__ == '__main__':
    fetch_data("399006")
    # get_market_score()
    # print(get_realtime_zt_count())